package com.lingyun.admin.controller.system.role;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.lingyun.common.exception.role.RoleHaveUserCanNotDelException;
import com.lingyun.common.pojo.LyRole;
import com.lingyun.common.utils.AjaxResult;
import com.lingyun.common.utils.file.FileDownloadUtils;
import com.lingyun.common.vo.role.RoleVagueQuery;
import com.lingyun.system.service.LyRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author 没事别学JAVA
 * 2021/12/16 0:48
 */
@RestController
@RequestMapping("/system/role")
@Api(value = "角色操作", description = "")
public class RoleController {


    @Resource
    LyRoleService lyRoleService;


    @ApiOperation(value = "查询角色列表（下拉框）")
    @GetMapping("/selectRole")
    public AjaxResult selectRole(){
        return AjaxResult.success(lyRoleService.selectRole());
    }

    /**
     * 获取所有角色
     * @param roleVagueQueryVo 角色搜索表单
     * @return 角色分页数据
     */
    @ApiOperation(value = "获取所有角色")
    @PreAuthorize("hasRole('system:role:rolelist')")
    @GetMapping("/roleList")
    public AjaxResult roleList(RoleVagueQuery roleVagueQueryVo){
        return AjaxResult.success(lyRoleService.roleList(roleVagueQueryVo));
    }

    /**
     * 删除角色
     * @param roleId  角色id
     * @return 是否删除成功
     */
    @ApiOperation(value = "删除角色")
    @PreAuthorize("hasRole('system:role:deleterolebyid')")
    @DeleteMapping("/deleteRoleById/{roleId}")
    public AjaxResult deleteRoleById(@PathVariable Long roleId){
        try {
            if(lyRoleService.deleteRoleById(roleId)){
                return AjaxResult.success("删除成功");
            }else {
                return AjaxResult.error("删除成功");
            }
        } catch (RoleHaveUserCanNotDelException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 批量删除角色
     * @param roleIds 角色id 集合
     * @return 是否删除成功
     */
    @ApiOperation(value = "批量删除角色")
    @PreAuthorize("hasRole('system:role:deleterolebyids')")
    @DeleteMapping("/deleteRoleByIds")
    public AjaxResult deleteRoleByIds(@RequestBody List<Long> roleIds){
        if(lyRoleService.removeByIds(roleIds)){
            return AjaxResult.success("删除成功");
        }else {
            return AjaxResult.error("删除成功");
        }
    }

    /**
     * 根据角色ID查询角色
     * @param roleId  角色ID
     * @return 角色信息
     */
    @ApiOperation(value = "根据角色ID查询角色")
    @PreAuthorize("hasRole('system:role:selectrolebyid')")
    @GetMapping("/selectRoleById/{roleId}")
    public AjaxResult selectRoleById(@PathVariable("roleId") Long roleId){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("role_data",lyRoleService.selectRoleById(roleId));
        return ajax;
    }

    /**
     * 角色修改
     * @param lyRole 角色信息表单
     * @return 是否修改成功
     */
    @ApiOperation(value = "角色修改")
    @PreAuthorize("hasRole('system:role:updaterole')")
    @PutMapping("/updateRole")
    public AjaxResult updateRole(@RequestBody LyRole lyRole){
        if(lyRoleService.updateRole(lyRole)>0){
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色+'"+lyRole.getRoleName()+"'失败！！");
    }

    /**
     * 修改角色状态
     * @param lyRole 角色信息表单（角色id,角色最新状态）
     * @return 角色状态是否修改成功
     */
    @ApiOperation(value = "修改角色状态")
    @PreAuthorize("hasRole('system:role:updaterolestatus')")
    @PutMapping("/updateRoleStatus")
    public AjaxResult updateRoleStatus(@RequestBody LyRole lyRole){
        if(lyRoleService.updateById(lyRole)){
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色状态失败！！");
    }

    /**
     * 添加角色
     * @param lyRole 角色信息表单
     * @return 是否添加成功
     */
    @ApiOperation(value = "添加角色")
    @PreAuthorize("hasRole('system:role:addrole')")
    @PostMapping("/addRole")
    public AjaxResult addRole(@RequestBody LyRole lyRole){
        if(lyRoleService.addRole(lyRole)>0){
            return AjaxResult.success();
        }
        return AjaxResult.error("角色添加失败");
    }

    /**
     * 角色信息导出为Excel
     * @param roleVagueQueryVo 角色搜索表单
     * @return
     */
    @ApiOperation(value = "角色信息导出为Excel")
    @PreAuthorize("hasRole('system:role:roleexportexcel')")
    @GetMapping("/roleExportExcel")
    public AjaxResult roleExportExcel(RoleVagueQuery roleVagueQueryVo){
        List<LyRole> lyRoleList = lyRoleService.roleExportExcel(roleVagueQueryVo);
        Workbook work= ExcelExportUtil.exportExcel(new ExportParams(),LyRole.class,lyRoleList);
        String filename = UUID.randomUUID().toString() + "_" + "角色数据" + ".xlsx";
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(FileDownloadUtils.getAbsoluteFile(filename));
            work.write(out);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success("导出成功",filename);
    }











}
